<?php

namespace app\common\model;

use think\Model;

class Nav extends Model
{
    protected $table = 'nav';
    public static function getIdByGid($gid)
    {
        return self::where('gid', $gid)->value('id');
    }
    public static function getTree($parent_id = 0)
    {
        $data = self::getCollection();
        return list2child($data->toArray(), $parent_id);
    }
    public static function treeList()
    {
        $data = self::order('sort')->select();
        return list2tree($data->toArray());
    }
    public static function getTreeByGid($gid)
    {
        $data = self::getCollection();
        $parent_id = null;
        foreach ($data as $v) {
            if($v['gid'] == $gid) {
                $parent_id = $v['id'];
            }
        }
        if($parent_id) {
            return list2child($data->toArray(), $parent_id);
        } else {
            return [];
        }
    }
    public static function getCrumbs($path)
    {
        $data = self::getCollection();
        $child = [];
        foreach ($data as $v) {
            if($v['path'] == $path) {
                $child = $v->toArray(); // 有的地址是相同的 这里匹配最后一个相同的
            }
        }
        if(empty($child)) return [];
        return getParentsList($data->toArray(), $child['id']);
    }
    private static function getCollection()
    {
        return self::order('sort desc')->order('parent_id')->select();
    }
}